package com.wlyuan.open.scanner.application.handler.table;

import com.alibaba.fastjson.JSON;
import com.wlyuan.open.scanner.application.annotation.TableScannerName;
import com.wlyuan.open.scanner.constant.ScannerCodeEnum;
import com.wlyuan.open.scanner.constant.TableEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author lijing
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
@TableScannerName(isDefault = false, tableName = TableEnum.ORDER_CACHE)
public class OrderCacheTableToIncrHandler extends BaseTableToIncrHandler {
    private static final String QUOTATION_STATUS = "Cache_PriceStatus";
    private static final String TOTAL_COST = "Cache_TotalCost";
    private static final String PAYABLE = "Index_Payable";
    private static final String PAYMENT = "Index_Payment";
    private static final String SUB = "Index_Paysub";

    @Override
    public List<String> handler(String tableName, String data, String beforeData) {
        // 新增 或者 报价状态变化 或者 总费用变化 或者 预付、到付、货到付有变化
        if (StringUtils.isBlank(beforeData) || !isChange(data, beforeData)) {
            return Arrays.asList(ScannerCodeEnum.QUOTATION.getName());
        }
        logger.error("{}报价状态变化 或者 总费用 或者 预付、到付、货到付无变化，不触发报价同步", tableName);
        return Collections.emptyList();

    }

    private boolean isChange(String data, String beforeData) {
        var dataMap = JSON.parseObject(data, Map.class);
        var beforeDataMap = JSON.parseObject(beforeData, Map.class);

        return String.valueOf(dataMap.get(QUOTATION_STATUS)).equals(String.valueOf(beforeDataMap.get(QUOTATION_STATUS))) &&
                String.valueOf(dataMap.get(TOTAL_COST)).equals(String.valueOf(beforeDataMap.get(TOTAL_COST))) &&
                String.valueOf(dataMap.get(PAYABLE)).equals(String.valueOf(beforeDataMap.get(PAYABLE))) &&
                String.valueOf(dataMap.get(PAYMENT)).equals(String.valueOf(beforeDataMap.get(PAYMENT))) &&
                String.valueOf(dataMap.get(SUB)).equals(String.valueOf(beforeDataMap.get(SUB)));

    }
}
